from common.serializers import ExcludeableSeri
from .models import *


class SDCategorySeri(ExcludeableSeri):

    def get_value(self, dictionary):
        cate = dictionary.get('category', 0)
        try:
            return SDCategory.objects.get(title=int(cate))
        except:
            return SDCategory.objects.get(title=0)

    def run_validation(self, data):
        return data

    class Meta:
        model = SDCategory
        fields = ('pk', 'title')


class SDRichPartSeri(ExcludeableSeri):

    def create(self, validated_data):
        obj = SDRichPart(**validated_data)
        obj.save()
        return obj

    class Meta:
        model = SDRichPart
        fields = ('pk', 'text', 'link', 'event')


class SDEventSeri(ExcludeableSeri):
    category = SDCategorySeri()
    event_parts = SDRichPartSeri(many=True, context={'excludes': ['event']})

    class Meta:
        model = SDEvent
        fields = ('pk', 'category', 'event_parts', 'date_str')
